package com.project.biz.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.core.result.BasePage;
import com.project.biz.*;
import com.project.common.enums.LockEnum;
import com.project.common.exception.ServiceException;
import com.project.common.utils.IpageToPage;
import com.project.entity.*;
import com.project.mapper.CmsOrderMapper;
import com.project.pojo.dto.*;
import com.project.pojo.model.*;
import com.project.redis.RedisClient2;
import com.project.util.Kuaidi100Util;
import com.project.util.wx.WxAuthUtil;
import com.project.util.wx.WxPaySignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 商品订单业务层接口实现类
 * @Author: zhuchi
 * @CreateDate: 2020/10/16 22:55
 * @Version: 1.0
 */
@Slf4j
@Service
public class CmsOrderBizImpl extends ServiceImpl<CmsOrderMapper, CmsOrder> implements CmsOrderBiz {

    /**
     * 注入自身
     */
    @Lazy
    @Autowired
    private CmsOrderBiz orderBiz;

    /**
     * 商品备份业务层接口类
     */
    @Autowired
    private CmsOrderProductBakBiz orderProductBakBiz;

    /**
     * 商品订单详情业务层接口类
     */
    @Autowired
    private CmsOrderDetailBiz orderDetailBiz;

    /**
     * 发票业务层接口类
     */
    @Autowired
    private CmsOrderInvoiceBiz orderInvoiceBiz;

    /**
     * 物流信息业务层接口类
     */
    @Autowired
    private CmsOrderLogisticsBiz orderLogisticsBiz;

    /**
     * 商品业务层接口类
     */
    @Autowired
    private CmsProductBiz productBiz;

    /**
     * 商品评价业务层接口类
     */
    @Autowired
    private CmsProductEvaBiz productEvaBiz;

    /**
     * 商品SKU业务层接口类
     */
    @Autowired
    private CmsProductSkuBiz productSkuBiz;

    /**
     * 用户业务层接口类
     */
    @Autowired
    private UserBiz userBiz;

    /**
     * 用户余额接口类
     */
    @Autowired
    private CmsUserBalanceBiz userBalanceBiz;

    /**
     * 地址管理业务层接口类
     */
    @Autowired
    private CmsUserAddressBiz userAddressBiz;

    /**
     * Redis服务
     */
    @Autowired
    private RedisClient2 redisClient2;

    /**
     * 资金流水业务层接口类
     */
    @Autowired
    private CmsCapitalFlowBiz capitalFlowBiz;

    /**
     * 用户购买商品下单后,最迟多久不支付,将执行系统取消订单（单位：小时）
     */
    @Value("${project.productOrderDeadlineTime}")
    private Integer productOrderDeadlineTime;

    /**
     * 商品订单用户签收后,最迟多久系统默认确认收货（单位：天）
     */
    @Value("${project.defaultConfirmation}")
    private Integer defaultConfirmation;

    /**
     * 商品订单确认收货后,最迟多久系统自动评价（单位：天）
     */
    @Value("${project.defaultEvaluation}")
    private Integer defaultEvaluation;

    /**
     * 微信支付通知信息业务层接口类
     */
    @Autowired
    private CmsWxPayNoticeBiz wxPayNoticeBiz;

    /**
     * 商品下单
     * @param createOrderModel
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 40)
    public CreateOrderDTO createOrder(CreateOrderModel createOrderModel, Long userId){
        //锁定购买的商品,购买的商品都可加锁时才能执行订单操作
        boolean createOrderLock = true;
        //存储分布式锁信息
        Map<String, Long> lockMap = new HashMap<>();

        List<Long> productIds = new ArrayList<>();
        for (CreateOrderProductModel orderProductModel : createOrderModel.getCreateOrderProductModels()){
            //去重复,防止用户对同一商品,不同规格购买时无法购买问题
            if (!productIds.contains(orderProductModel.getProductId())){
                productIds.add(orderProductModel.getProductId());
            }
        }

        //商品加锁,方式用户同时购买同一商品
        for (Long productId : productIds){
            //商品下单分布式锁
            String createOrder_lock = LockEnum.CREATE_ORDER.Value() + productId;
            //超时时间（15秒）
            Long expires = System.currentTimeMillis() + Long.parseLong(LockEnum.LOCK_EXPIRES.Value());
            //锁定购买的商品
            boolean productLock = this.redisClient2.lock(createOrder_lock, String.valueOf(expires));
            if (productLock == false){
                createOrderLock = false;
                break;
            }else {
                lockMap.put(createOrder_lock, expires);
            }
        }

        if (createOrderLock){
            try {
                //购买总数
                Integer quantity = 0;
                //订单总金额
                BigDecimal totalAmount = new BigDecimal("0.00");

                //订单商品信息
                List<CmsOrderDetail> orderDetails = new ArrayList<>();

                //购买的商品名称
                String productNames = "";
                for (CreateOrderProductModel createOrderProductModel : createOrderModel.getCreateOrderProductModels()){
                    CmsOrderDetail orderDetail = new CmsOrderDetail();
                    //验证商品
                    CmsProduct product = this.productBiz.getById(createOrderProductModel.getProductId());
                    //商品不存在、商品已被删除、商品已下架都提示用户"商品已下架"
                    if (null == product){
                        throw new ServiceException("商品已下架");
                    }else if (product.getStatus() == -1 || product.getState() == 0){
                        throw new ServiceException("商品["+product.getName()+"]已下架");
                    }

                    //验证商品规格
                    CmsProductSku productSku = this.productSkuBiz.getById(createOrderProductModel.getSkuId());
                    if (null == productSku){
                        throw new ServiceException("该规格已下架");
                    }else if (productSku.getStock() < createOrderProductModel.getBuyNumber()){
                        throw new ServiceException("商品["+product.getName()+"]库存不足");
                    }

                    productNames = productNames + product.getName() + ",";

                    //备份商品
                    Long productBakId = this.orderProductBakBiz.addOrderProductBak(product, productSku);

                    //下单减库存
                    int updateProductSkuStock = this.productSkuBiz.updateProductSkuStock(productSku.getSkuId(), createOrderProductModel.getBuyNumber(), product.getName());
                    log.info("用户[{}]购买商品[{}],下单减库存执行状态:{}", userId, product.getName(), updateProductSkuStock);

                    //购买当前商品数量
                    BigDecimal buyNumber = new BigDecimal(String.valueOf(createOrderProductModel.getBuyNumber()));

                    //购买当前商品所需金额
                    BigDecimal itemTotalPrice = productSku.getPrice().multiply(buyNumber).setScale(2, BigDecimal.ROUND_HALF_UP);

                    orderDetail.setProductId(product.getProductId());
                    orderDetail.setProductBakId(productBakId);
                    orderDetail.setBuyNumber(createOrderProductModel.getBuyNumber());
                    orderDetail.setSkuId(productSku.getSkuId());
                    orderDetail.setTotalPrice(itemTotalPrice);
                    orderDetail.setUnitPrice(productSku.getPrice());

                    //计算总价格
                    totalAmount = totalAmount.add(itemTotalPrice);
                    //计算购买总数
                    quantity = quantity + createOrderProductModel.getBuyNumber();
                    orderDetails.add(orderDetail);
                }

                //当前时间
                Date nowTime = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

                //TODO 用户量大了以后,为了防止并发时订单号重复,需到数据库查询是否重复
                //订单号，生成规则：YT + 年月日时分秒 + 八位随机数，比如YT2020121015362054445148
                String orderNumber = "YT" + format.format(nowTime) + RandomStringUtils.randomNumeric(8);

                //获取收获地址信息
                CmsUserAddress userAddress = this.userAddressBiz.getById(createOrderModel.getAddressId());

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(nowTime);
                //当前时间加24小时
                calendar.add(Calendar.HOUR_OF_DAY, productOrderDeadlineTime);
                //微秒设置为0,防止mysql自动加一秒
                //MySQL数据库对于毫秒大于500的数据进行进位
                calendar.set(Calendar.MILLISECOND, 0);

                //最晚支付时间
                Date deadlineTime = calendar.getTime();

                //抵扣金额（余额抵扣）
                BigDecimal deductionAmount = new BigDecimal("0.00");

                //获取用户钱包金额
                BigDecimal balance = this.userBalanceBiz.getUserBalance(userId);

                //是否使用余额（1:使用,2:不使用）
                if (null != createOrderModel.getUseBalance() && createOrderModel.getUseBalance() == 1){
                    //余额小于订单总价时,抵扣金额为钱包总金额
                    if (balance.compareTo(totalAmount) == -1){
                        deductionAmount = balance;
                    }else {//余额大于等于订单总价时,抵扣金额为订单金额
                        deductionAmount = totalAmount;
                    }
                }

                CmsOrder order = new CmsOrder();
                order.setUserId(userId);
                order.setOrderNumber(orderNumber);
                order.setQuantity(quantity);
                order.setTotalAmount(totalAmount);
                order.setUseBalance(createOrderModel.getUseBalance());
                order.setDeductionAmount(deductionAmount);
                order.setReceiveName(userAddress.getName());
                order.setReceiveMobile(userAddress.getMobile());
                order.setReceiveAddress(userAddress.getAllAdress());
                order.setInvoiceRequired(createOrderModel.getInvoiceRequired());
                order.setCreateTime(nowTime);
                order.setDeadlineTime(deadlineTime);
                order.setRemarks(createOrderModel.getRemarks());
                order.setState(0);//订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                order.setStatus(1);

                //添加订单信息
                int addOrderState = this.baseMapper.insert(order);
                log.info("用户[{}]购买商品[{}]添加订单执行状态:{}", userId, productNames.substring(0, productNames.length() - 1), addOrderState);

                if (addOrderState > 0){
                    //添加订单详情
                    int addOrderDetailState = this.orderDetailBiz.addOrderDetail(orderDetails, order.getProductOrderId());
                    log.info("用户[{}]购买商品[{}]添加订单详情执行状态:{}", userId, productNames.substring(0, productNames.length() - 1), addOrderDetailState);

                    //是否需要发票（0:不需要,1:需要）
                    if (createOrderModel.getInvoiceRequired() == 1){
                        //添加发票信息
                        int addOrderInvoiceState = this.orderInvoiceBiz.addOrderInvoice(createOrderModel.getOrderInvoice(), order.getProductOrderId());
                        log.info("用户[{}]购买商品[{}]添加发票信息执行状态:{}", userId, productNames.substring(0, productNames.length() - 1), addOrderInvoiceState);
                    }

                    //抵扣金额大于0时扣除
                    if (deductionAmount.compareTo(new BigDecimal("0.00")) == 1){
                        //在余额中需抵扣金额转入冻结金额,如果取消订单再返还
                        int updateSubUserBalance = this.userBalanceBiz.updateSubUserBalance(userId, deductionAmount);

                        //增加用户冻结金额
                        int addUserFrozenAmount = this.userBalanceBiz.updateAddUserFrozenAmount(userId, deductionAmount);
                        log.info("用户[{}]购买商品[{}]余额扣除抵扣金额执行状态:{},增加冻结金额执行状态:{}", userId, productNames.substring(0, productNames.length() - 1), updateSubUserBalance, addUserFrozenAmount);

                        //添加消费记录
                        AddConsumeFlowDTO addConsumeFlowDTO = new AddConsumeFlowDTO();
                        addConsumeFlowDTO.setConsumeType(3);
                        addConsumeFlowDTO.setAmount(deductionAmount);
                        addConsumeFlowDTO.setIncomeName("购买商品");
                        addConsumeFlowDTO.setUserAmount(balance);
                        int addConsumeFlow = this.capitalFlowBiz.addConsumeFlow(addConsumeFlowDTO, userId);
                        log.info("用户[{}]购买商品余额抵扣,增加消费记录执行状态:{}", userId, addConsumeFlow);
                    }

                    //下单返回信息
                    CreateOrderDTO createOrderDTO = new CreateOrderDTO();
                    BeanUtils.copyProperties(order, createOrderDTO);

                    return createOrderDTO;
                }else {
                    throw new ServiceException("下单失败");
                }
            }catch (Exception e){
                log.info("商品下单时发生异常信息：{}", e.getMessage());
                throw new ServiceException(e.getMessage());
            }finally {
                //解锁
                for (String key : lockMap.keySet()){
                    this.redisClient2.unlock(key, String.valueOf(lockMap.get(key)));
                }
            }
        }else {
            //购买人数较多，请稍后再试
            throw new ServiceException("购买人数较多,请稍后再试");
        }
    }

    /**
     * 获取订单列表
     * @param getOrderListModel
     * @return
     */
    public BasePage<ProductOrderListDTO> getOrderList(GetOrderListModel getOrderListModel){
        Page<ProductOrderListDTO> page = new Page<>(getOrderListModel.getPageNo(), getOrderListModel.getPageSize());
        IPage<ProductOrderListDTO> iPage = this.baseMapper.getOrderList(page, getOrderListModel);

        if (null != iPage && null != iPage.getRecords() && iPage.getRecords().size() > 0){
            List<ProductOrderListItemDTO> productOrderListItemDTOS;
            for (ProductOrderListDTO orderListDTO : iPage.getRecords()){
                //获取订单商品信息
                productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(orderListDTO.getProductOrderId());
                orderListDTO.setOrderListItems(productOrderListItemDTOS);
            }
        }

        BasePage<ProductOrderListDTO> basePage = IpageToPage.toBasePage(iPage, ProductOrderListDTO.class);
        return basePage;
    }

    /**
     * 获取订单详情
     * @param orderId
     */
    public ProductOrderDetailDTO getProductOrderDetail(Long orderId){
        ProductOrderDetailDTO productOrderDetailDTO = new ProductOrderDetailDTO();

        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        if (null != order){
            BeanUtils.copyProperties(order, productOrderDetailDTO);

            //获取下单用户信息
            CmsUser orderUser = this.userBiz.getById(order.getUserId());
            //返回订单用户昵称
            productOrderDetailDTO.setWxNickname(orderUser.getWxNickname());
            //返回订单用户手机号
            productOrderDetailDTO.setMobile(orderUser.getMobile());

            //获取订单商品信息
            List<ProductOrderListItemDTO> productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(orderId);
            productOrderDetailDTO.setOrderListItems(productOrderListItemDTOS);

            //订单发票信息
            CmsOrderInvoice orderInvoice = new CmsOrderInvoice();
            if (order.getInvoiceRequired() == 1){//是否需要发票（0:不需要,1:需要）
                orderInvoice = this.orderInvoiceBiz.getInvoiceByOrderId(orderId);
            }
            productOrderDetailDTO.setOrderInvoice(orderInvoice);
        }else {
            throw new ServiceException("订单不存在");
        }

        return productOrderDetailDTO;
    }

    /**
     * 取消订单
     * @param orderId
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateCancelOrder(Long orderId, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        if (null != order){
            if (order.getState() != 0){
                throw new ServiceException("只有待付款时才能取消订单");
            }
            if (order.getUserId().equals(userId)){
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                order.setState(-1);
                order.setCloseTime(new Date());
                result = this.baseMapper.updateById(order);
                if (result > 0){
                    //获取订单商品信息
                    List<ProductOrderListItemDTO> productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(orderId);
                    for (ProductOrderListItemDTO productOrderListItemDTO : productOrderListItemDTOS){
                        //取消订单后,返还库存数量
                        int addProductSkuStock = this.productSkuBiz.updateAddProductSkuStock(productOrderListItemDTO.getSkuId(), productOrderListItemDTO.getBuyNumber());
                        log.info("取消订单后,返还商品SKU[{}]库存数量{}执行状态:{}", productOrderListItemDTO.getSkuId(), productOrderListItemDTO.getBuyNumber(), addProductSkuStock);
                    }

                    //抵扣金额大于0时,返还抵扣金额
                    if (order.getDeductionAmount().compareTo(new BigDecimal("0.00")) == 1){
                        //获取用户钱包金额
                        BigDecimal balance = this.userBalanceBiz.getUserBalance(userId);

                        //取消订单后冻结金额退回余额
                        int subUserFrozenAmount = this.userBalanceBiz.updateSubUserFrozenAmount(userId, order.getDeductionAmount());

                        //取消订单后,返还抵扣金额
                        int addUserBalance = this.userBalanceBiz.updateAddUserBalance(userId, order.getDeductionAmount());
                        log.info("取消商品订单后,返还用户[{}]抵扣金额到余额{}元执行状态:{}, 扣除用户冻结金额执行状态:{}", userId, order.getDeductionAmount(), addUserBalance, subUserFrozenAmount);

                        //添加收益记录
                        AddIncomeFlowDTO addIncomeFlowDTO = new AddIncomeFlowDTO();
                        addIncomeFlowDTO.setProfitType(4);
                        addIncomeFlowDTO.setAmount(order.getDeductionAmount());
                        addIncomeFlowDTO.setIncomeName("商品订单取消退回");
                        addIncomeFlowDTO.setUserAmount(balance);
                        int addIncomeFlow = this.capitalFlowBiz.addIncomeFlow(addIncomeFlowDTO, order.getUserId());
                        log.info("取消商品订单后,返还用户[{}]抵扣金额{},添加收益记录执行状态:{}", order.getUserId(), order.getDeductionAmount(), addIncomeFlow);
                    }
                }

            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 删除订单
     * @param orderId
     * @param userId
     * @return
     */
    public int updateDelOrder(Long orderId, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        if (null != order){
            if (order.getUserId().equals(userId)){
                //删除标志（-1:删除,1:正常）
                order.setStatus(-1);
                result = this.baseMapper.updateById(order);
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 订单支付
     * @param orderId
     * @param userId
     * @param ip
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public OrderPayDTO updateOrderPay(Long orderId, Long userId, String ip){
        OrderPayDTO result = new OrderPayDTO();
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        if (null != order){
            if (order.getState() == -1){
                throw new ServiceException("该订单已取消,不能付款");
            }
            if (order.getState() != 0){
                throw new ServiceException("只有待付款状态订单才可发起支付");
            }
            if (order.getUserId().equals(userId)){
                //订单总金额
                BigDecimal totalAmount = order.getTotalAmount();
                //抵扣金额（余额抵扣）
                BigDecimal deductionAmount = order.getDeductionAmount();
                //需补差价：订单总金额 - 余额抵扣金额
                BigDecimal wxPayAmount = totalAmount.subtract(deductionAmount);
                //需补差价大于0时,调用H5支付下单,返回微信支付链接,用户根据链接支付差价
                if (wxPayAmount.compareTo(new BigDecimal("0.00")) == 1){
                    //订单所有商品名称,长度超过30时,剩余部分展示...
                    String productNames = "";

                    //获取订单商品信息
                    List<ProductOrderListItemDTO> productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(orderId);
                    for (ProductOrderListItemDTO productOrderListItemDTO : productOrderListItemDTOS){
                        productNames += productOrderListItemDTO.getName()+",";
                    }
                    productNames = productNames.substring(0, productNames.length() - 1);
                    if (productNames.length() > 30){
                        productNames = productNames.substring(0, 30) + "...";
                    }

                    //需补差价转换为分
                    int h5PayAmount = wxPayAmount.multiply(new BigDecimal("100.00")).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    //组装调用H5支付下单参数,调用下单接口
                    WxPayH5CreateOrderDTO wxPayH5CreateOrderDTO = new WxPayH5CreateOrderDTO();
                    wxPayH5CreateOrderDTO.setDescription(productNames);
                    wxPayH5CreateOrderDTO.setOutTradeNo(order.getOrderNumber());
                    wxPayH5CreateOrderDTO.setTotal(h5PayAmount);
                    wxPayH5CreateOrderDTO.setPayerClientIp(ip);
                    wxPayH5CreateOrderDTO.setPaySysType(1);
                    wxPayH5CreateOrderDTO.setTimeExpire(order.getDeadlineTime());
                    WxPayH5CreateOrderResultDTO wxPayH5CreateOrderResultDTO = WxPaySignUtil.wxPayH5CreateOrder(wxPayH5CreateOrderDTO);
                    if (wxPayH5CreateOrderResultDTO.getCode().equals("200")){
                        result.setPayState(2);//支付状态（1:支付成功,2:需补差价）
                        try {
                            result.setH5Url(URLEncoder.encode(wxPayH5CreateOrderResultDTO.getH5Url(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }else {
                        log.info("订单[{}]发起微信H5支付下单时发生错误:{}", orderId, wxPayH5CreateOrderResultDTO.getMessage());
                        throw new ServiceException("支付失败");
                    }
                }else {
                    //支付单号
                    String tradeNo = RandomStringUtils.randomAlphanumeric(32);
                    int balancePayState = this.orderBiz.updateOrderPaySuccess(orderId, new Date(), tradeNo, totalAmount);
                    if (balancePayState > 0){
                        result.setPayState(1);//支付状态（1:支付成功,2:需补差价）
                    }
                }
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * JSAPI支付
     * @param orderPayJsapiModel
     * @param userId
     * @param ip
     * @return
     */
    public OrderPayJsapiDTO updateOrderPayJsapi(OrderPayJsapiModel orderPayJsapiModel, Long userId, String ip){
        OrderPayJsapiDTO payJsapiDTO = new OrderPayJsapiDTO();
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderPayJsapiModel.getOrderId());
        if (null != order){
            if (order.getState() == -1){
                throw new ServiceException("该订单已取消,不能付款");
            }
            if (order.getState() != 0){
                throw new ServiceException("只有待付款状态订单才可发起支付");
            }
            if (order.getUserId().equals(userId)){
                //订单总金额
                BigDecimal totalAmount = order.getTotalAmount();
                //抵扣金额（余额抵扣）
                BigDecimal deductionAmount = order.getDeductionAmount();
                //需补差价：订单总金额 - 余额抵扣金额
                BigDecimal wxPayAmount = totalAmount.subtract(deductionAmount);
                //需补差价大于0时,调用JSAPI支付下单,返回前端JSAPI调起微信支付
                if (wxPayAmount.compareTo(new BigDecimal("0.00")) == 1){
                    //订单所有商品名称,长度超过30时,剩余部分展示...
                    String productNames = "";

                    //获取订单商品信息
                    List<ProductOrderListItemDTO> productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(orderPayJsapiModel.getOrderId());
                    for (ProductOrderListItemDTO productOrderListItemDTO : productOrderListItemDTOS){
                        productNames += productOrderListItemDTO.getName()+",";
                    }
                    productNames = productNames.substring(0, productNames.length() - 1);
                    if (productNames.length() > 30){
                        productNames = productNames.substring(0, 30) + "...";
                    }

                    //需补差价转换为分
                    int h5PayAmount = wxPayAmount.multiply(new BigDecimal("100.00")).setScale(2, BigDecimal.ROUND_HALF_UP).intValue();

                    String openId = "";
                    CmsUser user = this.userBiz.getById(userId);
                    if (StringUtils.isNotBlank(user.getWxOpenId())){
                        openId = user.getWxOpenId();
                    }else {
                        JSONObject jsonObject = WxAuthUtil.getOpenIdByCode(orderPayJsapiModel.getCode());
                        System.out.println("根据Code获取用户OpenId返回结果:" + jsonObject);
                        if (jsonObject.containsKey("openid")){
                            openId = jsonObject.getString("openid");
                            //为用户设置OpenId
                            user.setWxOpenId(openId);
                            this.userBiz.updateById(user);
                        }else {
                            log.info("根据CODE[{}]获取用户openid失败,失败原因:{}", orderPayJsapiModel.getCode(), jsonObject.getString("errmsg"));
                            throw new ServiceException("支付失败");
                        }
                    }

                    //组装调用H5支付下单参数,调用下单接口
                    WxPayJSAPICreateOrderDTO wxPayJSAPICreateOrderDTO = new WxPayJSAPICreateOrderDTO();
                    wxPayJSAPICreateOrderDTO.setDescription(productNames);
                    wxPayJSAPICreateOrderDTO.setOutTradeNo(order.getOrderNumber());
                    wxPayJSAPICreateOrderDTO.setTotal(h5PayAmount);
                    wxPayJSAPICreateOrderDTO.setPayerClientIp(ip);
                    wxPayJSAPICreateOrderDTO.setPaySysType(1);
                    wxPayJSAPICreateOrderDTO.setTimeExpire(order.getDeadlineTime());
                    wxPayJSAPICreateOrderDTO.setOpenId(openId);
                    payJsapiDTO = WxPaySignUtil.wxPayJSAPICreateOrder(wxPayJSAPICreateOrderDTO);
                    if (payJsapiDTO.getCode().equals("200")){
                        payJsapiDTO.setPayState(2);//支付状态（1:支付成功,2:需补差价）
                    }else {
                        log.info("订单[{}]发起微信JSAPI支付下单时发生错误:{}", orderPayJsapiModel.getOrderId(), payJsapiDTO.getMessage());
                        throw new ServiceException("支付失败");
                    }
                }else {
                    //支付单号
                    String tradeNo = RandomStringUtils.randomAlphanumeric(32);
                    int balancePayState = this.orderBiz.updateOrderPaySuccess(orderPayJsapiModel.getOrderId(), new Date(), tradeNo, totalAmount);
                    if (balancePayState > 0){
                        payJsapiDTO.setPayState(1);//支付状态（1:支付成功,2:需补差价）
                    }
                }
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return payJsapiDTO;
    }

    /**
     * 商品订单支付成功更新订单状态
     * @param orderId 订单ID
     * @param payTime 支付时间
     * @param tradeNo 支付单号
     * @param payAmount 支付金额
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateOrderPaySuccess(Long orderId, Date payTime, String tradeNo, BigDecimal payAmount){
        int result = 0;
        //商品订单支付成功更新订单状态分布式锁
        String updateOrderPaySuccess_lock = LockEnum.UPDATE_ORDER_PAY_SUCCESS.Value() + orderId;
        //超时时间（15秒）
        Long expires = System.currentTimeMillis() + Long.parseLong(LockEnum.LOCK_EXPIRES.Value());
        //锁定订单
        boolean orderLock = this.redisClient2.lock(updateOrderPaySuccess_lock, String.valueOf(expires));

        if (orderLock){
            try {
                //获取订单信息
                CmsOrder order = this.baseMapper.selectById(orderId);
                order.setTradeNo(tradeNo);
                order.setPayAmount(payAmount);
                order.setPayTime(payTime);
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                order.setState(1);
                result = this.baseMapper.updateById(order);

                if (result > 0){
                    //获取订单商品信息
                    List<CmsOrderDetail> list = this.orderDetailBiz.getProductOrderDetails(orderId);
                    for (CmsOrderDetail orderDetail : list){
                        //增加SKU单品销量
                        this.productSkuBiz.addSkuSales(orderDetail.getSkuId(), orderDetail.getBuyNumber());
                        //增加商品总销量
                        this.productBiz.addProductSales(orderDetail.getProductId(), orderDetail.getBuyNumber());
                    }

                    //抵扣金额大于0时,从冻结金额减去抵扣金额
                    if (order.getDeductionAmount().compareTo(new BigDecimal("0.00")) == 1){
                        //支付成功后,从冻结金额减去抵扣金额
                        int subUserFrozenAmount = this.userBalanceBiz.updateSubUserFrozenAmount(order.getUserId(), order.getDeductionAmount());
                        log.info("支付成功后,从用户[{}]钱包冻结金额中减去抵扣金额[{}]执行状态:{}", order.getUserId(), order.getDeductionAmount(), subUserFrozenAmount);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("商品订单支付成功更新订单状态时发生异常:{}", e.getMessage());
                throw new ServiceException("支付成功更新订单状态失败");
            }finally {
                this.redisClient2.unlock(updateOrderPaySuccess_lock, String.valueOf(expires));
            }
        }else {
            throw new ServiceException("操作太频繁了，请稍后再试");
        }

        return result;
    }

    /**
     * 微信商品支付成功
     * @param jsonObject
     * @return 0:失败,1:成功,2:已处理过,3:订单不存在
     */
    public int updateOrderH5PayNotify(JSONObject jsonObject){
        int result = 0;
        //商户订单号
        String out_trade_no = jsonObject.getString("out_trade_no");

        if (StringUtils.isNotBlank(out_trade_no)){
            //根据订单号获取订单信息
            CmsOrder order = this.getOrderByOrderNumber(out_trade_no);
            if (null != order){
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                if (order.getState() == 0){
                    //H5支付成功更新订单状态分布式锁
                    String updateOrderH5PayNotify_lock = LockEnum.UPDATE_ORDER_H5PAY_NOTIFY.Value() + out_trade_no;
                    //超时时间（15秒）
                    Long expires = System.currentTimeMillis() + Long.parseLong(LockEnum.LOCK_EXPIRES.Value());
                    //锁定订单
                    boolean orderLock = this.redisClient2.lock(updateOrderH5PayNotify_lock, String.valueOf(expires));
                    if (orderLock){
                        //交易类型(JSAPI:公众号支付,NATIVE:扫码支付,APP:app支付,MICROPAY:付款码支付,MWEB:H5支付,FACEPAY:刷脸支付)
                        String tradeType = jsonObject.getString("trade_type");
                        //微信支付订单号
                        String transaction_id = jsonObject.getString("transaction_id");

                        //支付完成时间
                        String success_time = jsonObject.getString("success_time");
                        success_time = success_time.replace("T", " ");
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        //用户支付金额，单位为分
                        Integer payer_total = jsonObject.getJSONObject("amount").getInteger("payer_total");
                        //用户支付金额,转为元
                        BigDecimal payAmount = new BigDecimal(String.valueOf(payer_total)).divide(new BigDecimal("100.00"), 2, BigDecimal.ROUND_HALF_UP);
                        try {
                            Date payTime = dateFormat.parse(success_time);
                            //更新订单状态
                            int updateOrderState = this.orderBiz.updateOrderPaySuccess(order.getProductOrderId(), payTime, transaction_id, payAmount);
                            log.info("商品订单使用微信{}支付成功,更新订单状态执行结果:{}", tradeType, updateOrderState);
                            if (updateOrderState > 0){
                                result = 1;

                                //获取用户钱包金额
                                BigDecimal balance = this.userBalanceBiz.getUserBalance(order.getUserId());

                                //添加消费记录
                                AddConsumeFlowDTO addConsumeFlowDTO = new AddConsumeFlowDTO();
                                addConsumeFlowDTO.setConsumeType(1);//消费类型（1:购买商品实付,2:购买商品抵扣,3:接单,4:实际金额大于预估金额补差价,5:系统扣款）
                                addConsumeFlowDTO.setPayType(2);//支付方式（0:银行卡,1:支付宝,2:微信）
                                addConsumeFlowDTO.setAmount(payAmount);
                                addConsumeFlowDTO.setIncomeName("购买商品"+tradeType+"支付");
                                addConsumeFlowDTO.setUserAmount(balance);
                                int addConsumeFlow = this.capitalFlowBiz.addConsumeFlow(addConsumeFlowDTO, order.getUserId());
                                log.info("用户[{}]购买商品使用微信{}付款支付[{}]元,增加消费记录执行状态:{}", order.getUserId(), tradeType, payAmount, addConsumeFlow);
                            }
                        }catch (Exception e){
                            System.out.println("时间转换异常");
                        }finally {
                            this.redisClient2.unlock(updateOrderH5PayNotify_lock, String.valueOf(expires));
                        }

                        //保存微信支付异步通知信息
                        this.wxPayNoticeBiz.addWxPayNotice(tradeType, 1, jsonObject.toJSONString());
                    }
                }else {
                    result = 2;
                }
            }else {
                result = 3;
            }
        }else {
            result = 3;
        }

        return result;
    }

    /**
     * 根据订单号获取订单
     * @param orderNumber
     * @return
     */
    public CmsOrder getOrderByOrderNumber(String orderNumber){
        QueryWrapper<CmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number", orderNumber);
        CmsOrder order = this.baseMapper.selectOne(queryWrapper);

        return order;
    }

    /**
     * 商品订单发货
     * @param productOrderIssueModel
     * @param userId
     * @return
     */
    public int updateProductOrderIssue(ProductOrderIssueModel productOrderIssueModel, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(productOrderIssueModel.getProductOrderId());
        if (null != order){
            if (order.getState() != 1){
                throw new ServiceException("只有待发货状态订单才可发货");
            }

            order.setLogisticsNumber(productOrderIssueModel.getLogisticsNumber());
            order.setLogisticsCompany(productOrderIssueModel.getLogisticsCompany());
            order.setLogisticsCompanyCode(productOrderIssueModel.getLogisticsCompanyCode());
            order.setLogisticsCompanyImg(productOrderIssueModel.getLogisticsCompanyImg());
            order.setSendTime(new Date());
            //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
            order.setState(2);
            result = this.baseMapper.updateById(order);
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 查看物流
     * @param orderId
     * @return
     */
    public List<ProductOrderLogisticsDTO> getProductOrderLogistics(Long orderId){
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        List<ProductOrderLogisticsDTO> productOrderLogisticsDTOS = new ArrayList<>();
        if (null != order){
            //发货时间不为空时,说明该订单已发货,根据发货单号调用第三方获取物流信息
            if (null != order.getSendTime()){
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                productOrderLogisticsDTOS = this.orderLogisticsBiz.getOrderLogistics(order.getLogisticsCompanyCode(), order.getLogisticsNumber());

                ProductOrderLogisticsDTO productOrderLogisticsDTO = new ProductOrderLogisticsDTO();
                productOrderLogisticsDTO.setLogisticsInfo("商家已发货");
                productOrderLogisticsDTO.setLogisticsTime(format.format(order.getSendTime()));
                productOrderLogisticsDTOS.add(productOrderLogisticsDTO);
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return productOrderLogisticsDTOS;
    }

    /**
     * 确认收货
     * @param productOrderConfirmReceiptModel
     * @param userId
     * @return
     */
    public int updateProductOrderConfirmReceipt(ProductOrderConfirmReceiptModel productOrderConfirmReceiptModel, Long userId){
        //TODO 目前没有设置和验证支付密码
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(productOrderConfirmReceiptModel.getProductOrderId());
        if (null != order){
            if (order.getUserId().equals(userId)){
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                if (order.getState() != 2){
                    throw new ServiceException("该订单当前状态不能确认收货");
                }
                order.setReceiveTime(new Date());
                order.setState(3);
                result = this.baseMapper.updateById(order);
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 评价
     * @param productOrderEvaluateModel
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateProductOrderEvaluate(ProductOrderEvaluateModel productOrderEvaluateModel, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(productOrderEvaluateModel.getProductOrderId());
        if (null != order){
            if (order.getUserId().equals(userId)){
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                if (order.getState() != 3){
                    throw new ServiceException("该订单当前状态不能评价");
                }
                //获取订单商品信息
                List<ProductOrderListItemDTO> productOrderListItemDTOS = this.orderDetailBiz.getProductOrderDetailList(productOrderEvaluateModel.getProductOrderId());

                for (ProductOrderListItemDTO orderListItemDTO : productOrderListItemDTOS){
                    //按商品添加商品评论
                    this.productEvaBiz.addProductEva(productOrderEvaluateModel, orderListItemDTO.getProductId(), order.getProductOrderId(), orderListItemDTO.getProductOrderDetailId(), userId);
                }

                order.setState(4);
                order.setCompleteTime(new Date());
                result = this.baseMapper.updateById(order);
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 申请退款
     * @param productOrderApplyRefundModel
     * @param userId
     * @return
     */
    public int updateOrderApplyRefund(ProductOrderApplyRefundModel productOrderApplyRefundModel, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(productOrderApplyRefundModel.getProductOrderId());
        if (null != order){
            if (order.getState() == -1){
                throw new ServiceException("该订单已取消,不能申请退款");
            }else if (order.getState() == 0){
                throw new ServiceException("该订单未支付,不能申请退款");
            }else if (order.getState() == 4){
                throw new ServiceException("该订单已完成,不能申请退款");
            }else if (order.getState() == 5){
                throw new ServiceException("该订单正在退款中,不能重复申请");
            }else if (order.getState() == 6){
                throw new ServiceException("该订单已退款成功,不能重复申请");
            }else if (order.getState() == 7){
                throw new ServiceException("该订单已退款失败,请联系客服");
            }
            if (order.getUserId().equals(userId)){
                order.setRefundNo(RandomStringUtils.randomAlphanumeric(32));
                order.setReasons(productOrderApplyRefundModel.getReasons());
                order.setReasonsPostscript(productOrderApplyRefundModel.getReasonsPostscript());
                order.setApplyRefundTime(new Date());
                //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                order.setState(5);
                result = this.baseMapper.updateById(order);
            }else {
                throw new ServiceException("无权操作该订单");
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 同意退款
     * @param agreeProductOrderRefundModel
     * @param userId
     * @return
     */
    public int updateAgreeProductOrderRefund(AgreeProductOrderRefundModel agreeProductOrderRefundModel, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(agreeProductOrderRefundModel.getProductOrderId());
        if (null != order){
            if (order.getState() != 5){
                throw new ServiceException("该订单状态不能退款");
            }
            order.setRefundAmount(agreeProductOrderRefundModel.getRefundAmount());
            //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
            order.setState(5);
            result = this.baseMapper.updateById(order);

            if (result > 0){
                //TODO 需要调用微信接口退款,目前先直接模拟通过数据
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("out_trade_no", order.getRefundNo());
                jsonObject.put("event_type", "REFUND.SUCCESS");
                this.updateProductOrderRefundByNotify(jsonObject);
            }
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 拒绝退款
     * @param orderId
     * @param userId
     * @return
     */
    public int updateAgreeProductOrderRefund(Long orderId, Long userId){
        int result = 0;
        //获取订单信息
        CmsOrder order = this.baseMapper.selectById(orderId);
        if (null != order){
            if (order.getState() != 5){
                throw new ServiceException("订单状态已改变,拒绝退款失败");
            }
            //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
            order.setState(7);
            order.setFailTime(new Date());
            result = this.baseMapper.updateById(order);
        }else {
            throw new ServiceException("订单不存在");
        }

        return result;
    }

    /**
     * 根据微信退款异步通知信息更新订单状态
     * @param jsonObject 微信异步通知信息
     * @return 0:失败,1:成功,2:已处理过,3:订单不存在
     */
    @Transactional(rollbackFor = Exception.class , isolation = Isolation.REPEATABLE_READ, timeout = 30)
    public int updateProductOrderRefundByNotify(JSONObject jsonObject){
        int result = 0;
        //退款单号
        String out_trade_no = jsonObject.getString("out_trade_no");

        //根据微信退款异步通知信息更新订单状态分布式锁
        String updateProductOrderRefundByNotify_lock = LockEnum.UPDATE_PRODUCT_ORDER_REFUND_BY_NOTIFY.Value() + out_trade_no;
        //超时时间（15秒）
        Long expires = System.currentTimeMillis() + Long.parseLong(LockEnum.LOCK_EXPIRES.Value());
        //退款单号加锁
        if (this.redisClient2.lock(updateProductOrderRefundByNotify_lock, String.valueOf(expires))){
            try {
                CmsOrder order = this.getOrderByRefundNo(out_trade_no);

                if (null != order){
                    //订单状态（-1:已取消、0:待付款、1:待发货、2:待收货、3:待评价、4:已完成,5:退款中、6:退款成功、7:退款失败）
                    if (order.getState() != 5){
                        result = 2;
                    }else {
                        //退款成功
                        if (jsonObject.getString("event_type").equals("REFUND.SUCCESS")){
                            order.setState(6);
                            order.setSuccessTime(new Date());
                        }else {//退款失败
                            order.setState(7);
                            order.setFailTime(new Date());
                        }
                        result = this.baseMapper.updateById(order);
                    }
                }else {
                    result = 3;
                }
            }catch (Exception e){
                e.printStackTrace();
                throw new ServiceException(e.getMessage());
            }finally {
                //解锁
                this.redisClient2.unlock(updateProductOrderRefundByNotify_lock, String.valueOf(expires));
            }
        }else {
            //操作太频繁了，请稍后再试
            throw new ServiceException("操作太频繁了，请稍后再试");
        }

        return result;
    }

    /**
     * 根据退款单号查询订单信息
     * @param refundNo
     * @return
     */
    public CmsOrder getOrderByRefundNo(String refundNo){
        QueryWrapper<CmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_no", refundNo);
        return this.baseMapper.selectOne(queryWrapper);
    }

    /**
     * 定时查询超过24小时待付款的商品订单,执行系统取消操作
     */
    public int updateTimingToBePaidOrder(){
        int result = 0;
        //查询超过24小时待付款的商品订单
        List<CmsOrder> toBePaidOrders = this.baseMapper.selectToBePaidOrder();
        if (null != toBePaidOrders && toBePaidOrders.size() > 0){
            for (CmsOrder order : toBePaidOrders){
                try {
                    //调用取消订单方法
                    int cancalOrderState = this.orderBiz.updateCancelOrder(order.getProductOrderId(), order.getUserId());
                    log.info("超过24小时待付款的商品订单[{}],执行系统取消执行状态:{}", order.getProductOrderId(), cancalOrderState);
                    if (cancalOrderState > 0){
                        result++;
                    }
                }catch (Exception e){
                    log.info("超过24小时待付款的商品订单[{}],执行系统取消时发生异常:{}", order.getProductOrderId(), e.getMessage());
                }
            }
        }

        return result;
    }

    /**
     * 获取用户商品订单、回收订单各状态数量
     * @param userId
     * @return
     */
    public GetOrderNumDTO getUserProductOrderNum(Long userId){
        GetOrderNumDTO getOrderNumDTO = this.baseMapper.getUserProductOrderNum(userId);
        return getOrderNumDTO;
    }

    /**
     * 定时查询已签收7天后还未确认收货的订单,进行系统自动确认收货操作
     * @return
     */
    public int updateConfirmReceiptOrder(){
        int result = 0;
        //查询未确认收货的订单
        List<CmsOrder> confirmReceiptOrder = this.baseMapper.selectConfirmReceiptOrder();

        if (null != confirmReceiptOrder && confirmReceiptOrder.size() > 0){
            //当前时间
            Date nowTime = new Date();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (CmsOrder order : confirmReceiptOrder){
                try {
                    if (StringUtils.isNotBlank(order.getLogisticsCompanyCode()) && StringUtils.isNotBlank(order.getLogisticsNumber())){
                        //调用快递100接口查询物流信息
                        JSONObject jsonObject = Kuaidi100Util.logisticsQuery(order.getLogisticsCompanyCode(), order.getLogisticsNumber());

                        if (jsonObject.containsKey("status") && jsonObject.getString("status").equals("200")){
                            //物流状态：0在途，1揽收，2疑难，3签收，4退签，5派件，6退回，7转单，10待清关，11清关中，12已清关，13清关异常
                            if (jsonObject.getString("state").equals("3")){
                                JSONArray jsonArray = jsonObject.getJSONArray("data");
                                if (null != jsonArray && jsonArray.size() > 0){
                                    //获取最新一条物流
                                    JSONObject data = jsonArray.getJSONObject(0);
                                    //获取签收时间
                                    String signForTime = data.getString("time");
                                    Date signForDate = format.parse(signForTime);

                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTime(signForDate);
                                    //签收时间增加七天
                                    calendar.add(Calendar.DATE, defaultConfirmation);

                                    //签收七天后的时间
                                    Date signForDate7Day = calendar.getTime();

                                    //如果当前时间大于签收时间 + 7天,系统自动确认收货
                                    if (nowTime.getTime() > signForDate7Day.getTime()){
                                        ProductOrderConfirmReceiptModel productOrderConfirmReceiptModel = new ProductOrderConfirmReceiptModel();
                                        productOrderConfirmReceiptModel.setProductOrderId(order.getProductOrderId());
                                        //执行确认收货操作
                                        int confirmReceiptState = this.orderBiz.updateProductOrderConfirmReceipt(productOrderConfirmReceiptModel, order.getUserId());
                                        if (confirmReceiptState > 0){
                                            result++;
                                        }
                                    }
                                }
                            }
                        }else {
                            log.info("根据公司编码[{}]、物流单号[{}]查询物流信息失败,失败原因：{}", order.getLogisticsCompanyCode(), order.getLogisticsNumber(), jsonObject.getString("message"));
                        }
                    }
                }catch (Exception e){
                    log.info("处理已签收7天后还未确认收货的订单[{}],执行系统确认收货时发生异常:{}", order.getProductOrderId(), e.getMessage());
                }
            }
        }

        return result;
    }

    /**
     * 定时查询确认收货多少天后未评价的商品订单,执行系统自动评价操作
     * @return
     */
    public int updateToBeEvaluatedOrder(){
        int result = 0;
        //查询确认收货多少天后未评价的商品订单
        List<CmsOrder> selectToBeEvaluatedOrder = this.baseMapper.selectToBeEvaluatedOrder(defaultEvaluation);
        if (null != selectToBeEvaluatedOrder && selectToBeEvaluatedOrder.size() > 0){
            ProductOrderEvaluateModel productOrderEvaluateModel = new ProductOrderEvaluateModel();
            for (CmsOrder order : selectToBeEvaluatedOrder){
                try {
                    productOrderEvaluateModel.setProductOrderId(order.getProductOrderId());
                    //调用评价订单方法
                    int updateProductOrderEvaluate = this.orderBiz.updateProductOrderEvaluate(productOrderEvaluateModel, order.getUserId());
                    log.info("确认收货多少天后未评价的商品订单[{}],执行系统自动评价操作执行状态:{}", order.getProductOrderId(), updateProductOrderEvaluate);
                    if (updateProductOrderEvaluate > 0){
                        result++;
                    }
                }catch (Exception e){
                    log.info("确认收货多少天后未评价的商品订单[{}],执行系统自动评价操作时发生异常:{}", order.getProductOrderId(), e.getMessage());
                }
            }
        }

        return result;
    }

}
